/**
 * Created by kevin on 2017/6/2.
 */
var express = require('express');
var router = express.Router();
var Roles = require('../models/Roles');
var Users = require('../models/Users');
var Robots = require('../models/Robots');
var Applications = require('../models/Applications');

var GitUsers = require('../models/GitUsers');
var Repos = require('../models/Repos');

var Delegater = require('../models/Delegaters');

var Guanjia = require('../models/Guanjia');


var ucheck = require('../utils/ucheck');

router.get('/*',function (req,res,next) {
    ucheck.hasLogin(res,function (has) {
        if (!has) {
            req.flash('error', '请先登录');
            res.redirect('/user/login');
            return;
        }
        next();
    })
});

router.post('/*',function (req,res,next) {
    ucheck.hasLogin(res,function (has) {
        if (!has) {
            res.json({
                message : '请先登录',
                code : -1,
                data : null
            });
            return;
        }
        next();
    })
});


router.get('/',function (req,res,next) {
    let user = res.locals.user;
    if (user.root) {
        res.redirect('/admin/user');
    } else if (user.role) {
        let role = user.role;
        if (role.permissions.managerA || role.permissions.managerI) {
            res.redirect('/admin/robot');
        } else {
            res.redirect('/');
        }
    } else {
        res.redirect('/');
    }
});

/* GET package page. */
/**************** 管理员区  *******************  */
function rootCheck(res,cb) {
    ucheck.isRoot(res,function (is) {
        if (is) {
            cb();
        } else {
            res.json({
                message : '您权限不足',
                code : -1,
                data : null
            });
        }
    });
}

/*************************** 用户 *************************/
router.all('/user/*',function (req,res,next) {
    rootCheck(res,function () {
        next();
    })
});

router.get('/user',function (req,res,next) {
    rootCheck(res,function () {
        Roles.getAll(function (err,roles) {
            res.render('admin/user',{title:'用户管理',roles:roles});
        });
    });

});

router.post('/user/add',function (req,res,next) {
    let user = ({
        username : req.body['username'],
        nickname : req.body['nickname'],
        email : req.body['email'],
        passwd : req.body['passwd'],
        role : req.body['role']
    });
    Users.createUnique(user,function (err) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else {
            res.json({
                message : '成功',
                code : 0,
                data : null
            });
        }
    })
});

router.post('/user/edit',function (req,res,next) {
    let user = ({
        username : req.body['username'],
        nickname : req.body['nickname'],
        email : req.body['email'],
        role : req.body['role']
    });
    if (req.body['passwd']) {
        user.passwd = req.body['passwd'];
    }
    let id = req.body['id'];

    Users.edit(id,user,function (err,role) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else  {
            res.json({
                message : '成功',
                code : 0,
                data : role
            });
        }
    });
});

router.post('/user/list',function (req,res,next) {
    Users.getAll(function (err,users) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else  {
            res.json({
                message : '成功',
                code : 0,
                data : users
            });
        }
    });
});

router.post('/user/del',function (req,res,next) {
    let id = req.body['id'];
    Users.remove({'_id':id,'root':false},function (err) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else {
            res.json({
                message : '成功',
                code : 0,
                data : null
            });
        }
    });
});

/************************** 角色 ************************* */
router.all('/role/*',function (req,res,next) {
    rootCheck(res,function () {
        next();
    })
});

router.get('/role',function (req,res,next) {
    rootCheck(res,function () {
        res.render('admin/role', {title: '角色管理'});
    });
});

router.post('/role/add',function (req,res,next) {
    let role = ({
        name : req.body['name'],
        permissions : {
            managerA : req.body['managerA'],
            managerI : req.body['managerI'],
            packageI : req.body['packageI'],
            packageA : req.body['packageA'],
            article : req.body['article'],
            checkUser : req.body['checkUser']
        }
    });
    Roles.createUniqueName(role,function (err,role) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else  {
            res.json({
                message : '成功',
                code : 0,
                data : null
            });
        }
    });
});

router.post('/role/edit',function (req,res,next) {
    let role = ({
        name : req.body['name'],
        permissions : {
            managerA : req.body['managerA'],
            managerI : req.body['managerI'],
            packageI : req.body['packageI'],
            packageA : req.body['packageA'],
            article : req.body['article'],
            checkUser : req.body['checkUser']
        }
    });
    let id = req.body['roleId'];
    Roles.edit(id,role,function (err,role) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else  {
            res.json({
                message : '成功',
                code : 0,
                data : role
            });
        }
    });
});

router.post('/role/list',function (req,res,next) {
    Roles.getAll(function (err,roles) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else  {
            res.json({
                message : '成功',
                code : 0,
                data : roles
            });
        }
    })
});

router.post('/role/del',function (req,res,next) {
    let id = req.body['id'];
    Roles.remove({'_id':id},function (err) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else {
            res.json({
                message : '成功',
                code : 0,
                data : null
            });
        }
    });
});
/**************** AI(android/ios)管理员区  *******************  */
function AIManagerCheck(res,cb) {
    ucheck.AIManager(res,function (is) {
        if (is) {
            cb();
        } else {
            res.json({
                message : '对不起，您权限不足',
                code : -1,
                data : null
            });
        }
    });
}
/************************** 机器人 ************************* */

router.all('/robot/*',function (req,res,next) {
    rootCheck(res,function () {
        next();
    });
});

router.get('/robot',function (req,res,next) {
    rootCheck(res,function () {
        Roles.getAll(function (err,roles) {
            res.render('admin/robot',{title:'机器人管理'});
        });
    });
});

router.post('/robot/add',function (req,res,next) {
    let robot = ({
        name : req.body['name'],
        token : req.body['token']
    });
    Robots.createUnique(robot,function (err,role) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else  {
            res.json({
                message : '成功',
                code : 0,
                data : null
            });
        }
    });
});

router.post('/robot/edit',function (req,res,next) {
    let robot = ({
        name : req.body['name'],
        token : req.body['token']
    });
    let id = req.body['id'];
    Robots.edit(id,robot,function (err,role) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else  {
            res.json({
                message : '成功',
                code : 0,
                data : role
            });
        }
    });
});

router.post('/robot/list',function (req,res,next) {
    Robots.getAll(function (err,roles) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else  {
            res.json({
                message : '成功',
                code : 0,
                data : roles
            });
        }
    })
});

router.post('/robot/del',function (req,res,next) {
    let id = req.body['id'];
    Robots.remove({'_id':id},function (err) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else {
            res.json({
                message : '成功',
                code : 0,
                data : null
            });
        }
    });
});
/************************** 代理机 ************************* */

router.all('/delegater/*',function (req,res,next) {
    rootCheck(res,function () {
        next();
    });
});

router.get('/delegater',function (req,res,next) {
    rootCheck(res,function () {
        res.render('admin/delegater', {title: '代理机管理'});
    });
});

router.post('/delegater/add',function (req,res,next) {
    let delegater = ({
        name : req.body['name'],
        ip : req.body['ip'],
        platform : req.body['platform'],
        user : req.body['user'],
        type : req.body['type'],
        prefixScript : req.body['prefix'],
        suffixScript : req.body['suffix']
    });

    Delegater.createUniqueName(delegater,function (err,dele) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else  {
            res.json({
                message : '成功',
                code : 0,
                data : null
            });
        }
    });
});

router.post('/delegater/edit',function (req,res,next) {
    let delegater = ({
        name : req.body['name'],
        ip : req.body['ip'],
        platform : req.body['platform'],
        user : req.body['user'],
        type : req.body['type'],
        prefixScript : req.body['prefix'],
        suffixScript : req.body['suffix']
    });
    let id = req.body['id'];
    Delegater.edit(id,delegater,function (err,dele) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else  {
            res.json({
                message : '成功',
                code : 0,
                data : null
            });
        }
    });
});

router.post('/delegater/list',function (req,res,next) {
    Delegater.getAll(function (err,delegaters) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else  {
            res.json({
                message : '成功',
                code : 0,
                data : delegaters
            });
        }
    })
});

router.post('/delegater/del',function (req,res,next) {
    let id = req.body['id'];
    Delegater.remove({'_id':id},function (err) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else {
            res.json({
                message : '成功',
                code : 0,
                data : null
            });
        }
    });
});
/************************** git账号 ************************* */
router.all('/gituser/*',function (req,res,next) {
    rootCheck(res,function () {
        next();
    });
});

router.get('/gituser',function (req,res,next) {
    rootCheck(res,function () {
        res.render('admin/gituser',{title:'Git用户管理'});
    });
});

router.post('/gituser/add',function (req,res,next) {
    let gituser = ({
        name : req.body['name'],
        username : req.body['username'],
        passwd : req.body['passwd']
    });
    GitUsers.createUnique(gituser,function (err) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else  {
            res.json({
                message : '成功',
                code : 0,
                data : null
            });
        }
    });
});

router.post('/gituser/edit',function (req,res,next) {
    let gituser = ({
        name : req.body['name'],
        username : req.body['username'],
        passwd : req.body['passwd']
    });
    let id = req.body['id'];
    GitUsers.edit(id,gituser,function (err) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else  {
            res.json({
                message : '成功',
                code : 0,
                data : null
            });
        }
    });
});

router.post('/gituser/list',function (req,res,next) {
    GitUsers.getAll(function (err,gitusers) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else  {
            res.json({
                message : '成功',
                code : 0,
                data : gitusers
            });
        }
    })
});

router.post('/gituser/del',function (req,res,next) {
    let id = req.body['id'];
    GitUsers.remove({'_id':id},function (err) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else {
            res.json({
                message : '成功',
                code : 0,
                data : null
            });
        }
    });
});

/************************** repo ************************* */

router.all('/repo/*',function (req,res,next) {
    rootCheck(res,function () {
        next();
    });
});

router.get('/repo',function (req,res,next) {
    rootCheck(res,function () {
        res.render('admin/repo',{title:'Repo管理'});
    });
});

router.post('/repo/add',function (req,res,next) {
    let repo = ({
        name : req.body['name'],
        url : req.body['url']
    });
    Repos.createUnique(repo,function (err) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else  {
            res.json({
                message : '成功',
                code : 0,
                data : null
            });
        }
    });
});

router.post('/repo/edit',function (req,res,next) {
    let repo = ({
        name : req.body['name'],
        url : req.body['url']
    });
    let id = req.body['id'];
    Repos.edit(id,repo,function (err) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else  {
            res.json({
                message : '成功',
                code : 0,
                data : null
            });
        }
    });
});

router.post('/repo/list',function (req,res,next) {
    Repos.getAll(function (err,repos) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else  {
            res.json({
                message : '成功',
                code : 0,
                data : repos
            });
        }
    })
});

router.post('/repo/del',function (req,res,next) {
    let id = req.body['id'];
    Repos.remove({'_id':id},function (err) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else {
            res.json({
                message : '成功',
                code : 0,
                data : null
            });
        }
    });
});

/************************** 包管理器配置 ************************* */

router.all('/guanjia/*',function (req,res,next) {
    rootCheck(res,function () {
        next();
    });
});

router.get('/guanjia',function (req,res) {
    Guanjia.getInfo(function (err,guanjia) {
        Applications.getListByType(1,function (err,ios_list) {
            Applications.getListByType(2,function (err,android_list) {
                console.log("ios : " + JSON.stringify(ios_list))
                console.log("android : " + JSON.stringify(android_list))
                res.render('admin/guanjia',{title:'包管理器配置',guanjia:guanjia,ios:ios_list,android:android_list});
            });
        });
    });

});

router.post('/guanjia/edit',function (req,res) {
    var ios = req.body.ios;
    var android = req.body.android;

    if (ios.length === 0) {
        ios = null;
    }
    if (android.length === 0) {
        android = null;
    }
    var config = {
        name : req.body.name,
        desc : req.body.desc,
        ios : ios,
        android: android
    };
    Guanjia.config(config,function (err) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else {
            res.json({
                message : '成功',
                code : 0,
                data : null
            });
        }
    });
});

module.exports = router;
